package com.atm.atmsys.controller.account;


import com.atm.atmsys.Service.AccountService;
import com.atm.atmsys.Service.TransactionService;
import com.atm.atmsys.Service.UserService;
import com.atm.atmsys.dto.*;
import com.atm.atmsys.entity.AccountInfo;
import com.atm.atmsys.entity.PageResult;
import com.atm.atmsys.utils.Result;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/account")
@Slf4j
public class AccountController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private UserService userService;

    @Autowired
    private TransactionService transactionService;

    @Autowired
    HttpServletRequest request;

    //添加账户
    @PostMapping("/addAccount")
    @ApiOperation("新增账户")
    public Result<String> addAdmin(@RequestBody AccountInfo accountInfo) {
        log.info("新增账户:{}",accountInfo);
        if (userService.getBySF(accountInfo.getIdentification()) == null) {
            return Result.error("该用户不存在");
        }
        accountService.addAccount(accountInfo);
        return Result.success(accountInfo.getCardNo());


    }

    //获取所有卡号
    @PostMapping("/getAllCardNO")
    @ApiOperation("获取所有卡号")
    public Result getAllCardNO() {
        return Result.success(accountService.getAllCardNO());
    }

    //根据身份证获取卡号
    @GetMapping("/getCardNO/{identification}")
    @ApiOperation("根据身份证获取卡号")
    public Result<List<String>> getCardNO(@PathVariable String identification) {
        List<String> cardNOList = accountService.getCardNOByIdentification(identification);
        return Result.success(cardNOList);
    }
    //删除账户
    @DeleteMapping("/deleteAccount/{cardno}")
    @ApiOperation("根据卡号删除账户")
    public Result deleteAccount(@PathVariable String cardno) {
        if(accountService.getAccountStatusByCardNO(cardno)==null){
            return Result.error("该账户不存在");
        }
        accountService.deleteAccount(cardno);
        log.info("删除账户:{}",cardno);
        return Result.success();
    }


    //修改账户状态
    @PutMapping("/updateAccountStatus")
    @ApiOperation("更新账户状态")
    public Result updateAccountStatus(@RequestBody AccountStatusDTO accountStatusDTO) {
        if(accountStatusDTO.getAccountStatus().equals("active")||accountStatusDTO.getAccountStatus().equals("frozen")){
            accountService.updateAccountStatus(accountStatusDTO);
            return Result.success();

        }
        return Result.error("请输入正确状态");
    }


    //查询账户余额
    @GetMapping("/getBalance/{cardNo}")
    @ApiOperation("查询账户余额")
    public Result<String> getBalance(@PathVariable String cardNo){
        String balance=accountService.getBalanceByCardNO(cardNo);
        return Result.success("账户余额为："+balance);
    }


    //根据卡号查询账户状态
    @GetMapping("/getAccountStatus/{cardNo}")
    @ApiOperation("根据卡号查询账户状态")
    public Result<String> getAccountStatus(@PathVariable String cardNo){
        String status = accountService.getAccountStatusByCardNO(cardNo);
        return Result.success("账户状态为："+status);
    }

    //存钱
    @PutMapping("/saveMoney")
    @ApiOperation("存款")
    public Result saveMoney(@RequestBody SaveMoneyDTO saveMoneyDTO){
        try {
            if(accountService.getAccountStatusByCardNO(saveMoneyDTO.getCardNo()).equals("active")){
                accountService.saveMoney(saveMoneyDTO);
                TransactionRecordDTO transactionRecordDTO=new TransactionRecordDTO();
                transactionRecordDTO.setCardNo1(saveMoneyDTO.getCardNo());
                transactionRecordDTO.setMoney(BigDecimal.valueOf(saveMoneyDTO.getMoney()));
                transactionRecordDTO.setStatus("save");
                transactionService.addTransactionWithoutChangeMysql(transactionRecordDTO);
                return Result.success();
            }
            return Result.error("账户状态异常");
        } catch (Exception e) {
            return Result.error("请先登录");
        }
    }

    //取钱
    @PutMapping("/drawMoney")
    @ApiOperation("取款")
    public Result drawMoney(@RequestBody DrawMoneyDTO drawMoneyDTO ) {
        try {
            if(accountService.getAccountStatusByCardNO(drawMoneyDTO.getCardNo()).equals("active")){
                double balance=Double.valueOf(accountService.getBalanceByCardNO(drawMoneyDTO.getCardNo()));
                if(balance>=drawMoneyDTO.getMoney()){
                    accountService.drawMoney(drawMoneyDTO);
                }else {
                    return Result.error("余额不足");
                }
                TransactionRecordDTO transactionRecordDTO=new TransactionRecordDTO();
                transactionRecordDTO.setCardNo1(drawMoneyDTO.getCardNo());
                transactionRecordDTO.setMoney(BigDecimal.valueOf(drawMoneyDTO.getMoney()));
                transactionRecordDTO.setStatus("withdraw");
                transactionService.addTransactionWithoutChangeMysql(transactionRecordDTO);
                return Result.success();
            }else {
                return Result.error("账户状态异常");
            }
        } catch (NumberFormatException e) {
            return Result.error("请先登录");
        }
    }

    //根据卡号进行账户过户
    @PutMapping("/transfer")
    @ApiOperation("银行卡过户")
    public Result transfer(@RequestBody AccountTransDTO accountTransDTO){
        if (userService.getBySF(accountTransDTO.getIdentification()) != null) {
            accountService.transfer(accountTransDTO);
            return Result.success();

        }
        return Result.error("该用户不存在,无法进行账户过户");
    }

    //转账
    @PutMapping("/transaction")
    @ApiOperation("转账")
    public Result transfer(@RequestBody TransferDTO transferDTO) {
        try {
            DrawMoneyDTO drawMoneyDTO = new DrawMoneyDTO();
            drawMoneyDTO.setCardNo(transferDTO.getCardNo1());
            drawMoneyDTO.setMoney(transferDTO.getMoney());

            SaveMoneyDTO saveMoneyDTO = new SaveMoneyDTO();
            saveMoneyDTO.setCardNo(transferDTO.getCardNo2());
            saveMoneyDTO.setMoney(transferDTO.getMoney());


            if(accountService.getAccountStatusByCardNO(drawMoneyDTO.getCardNo()).equals("active")&&accountService.getAccountStatusByCardNO(saveMoneyDTO.getCardNo()).equals("active")){

                double balance=Double.valueOf(accountService.getBalanceByCardNO(drawMoneyDTO.getCardNo()));
                if(balance>=drawMoneyDTO.getMoney()){
                    accountService.drawMoney(drawMoneyDTO);
                }else {
                    return Result.error("余额不足");
                }

                accountService.saveMoney(saveMoneyDTO);

                TransactionRecordDTO transactionRecordDTO=new TransactionRecordDTO();
                transactionRecordDTO.setCardNo1(drawMoneyDTO.getCardNo());
                transactionRecordDTO.setCardNo2(saveMoneyDTO.getCardNo());
                transactionRecordDTO.setMoney(BigDecimal.valueOf(drawMoneyDTO.getMoney()));
                transactionRecordDTO.setStatus("transfer");
                transactionService.addTransactionWithoutChangeMysql(transactionRecordDTO);

                return Result.success();
            }else {
                return Result.error("账户状态异常");
            }
        } catch (Exception e) {
            return Result.error("请先登录");
        }

    }

    //根据卡号查询账户是否存在
    @PostMapping("/checkExistByCardNo/{cardNo}")
    @ApiOperation("根据卡号查询账户是否存在")
    public Result<AccountInfo> checkExistByCardNo(@PathVariable String cardNo){

        AccountInfo accountInfo=accountService.getAccountByCardNO(cardNo);
        if (accountInfo==null)
            return Result.error("该卡号"+cardNo+"不存在");

        return Result.success(accountInfo);
    }

    //查询所有账户信息
    @GetMapping("/getAllAccount")
    @ApiOperation("查询所有账户信息")
    public Result<PageResult> pageAccount(AccountPageDTO accountPageDTO){
        log.info("管理员分页查询，参数为：{}",accountPageDTO);
        PageResult pageResult=accountService.pageQueryAccount(accountPageDTO);
        return Result.success(pageResult);

    }

}
